# -*- coding: utf-8 -*-
from urllib import request
import urllib
from urllib import parse

# response = request.urlopen("http://www.baidu.com")
# print(response.read().decode('utf-8'))

"""
    获取一个POST请求
"""

# 封装 POST 请求格式数据
# data = bytes(parse.urlencode({"hello": "jessica"}), encoding="utf-8")
# response = request.urlopen('https://httpbin.org/post', data=data)
# print(response.read().decode("utf-8"))

"""
    超时处理
"""
# try:
#     response = request.urlopen('https://httpbin.org/get', timeout=3)
#     print(response.read().decode("utf-8"))
# except urllib.error.URLError as e:
#     print(response.url, "Timeout!!!")

"""
    响应头
"""
# response = request.urlopen('https://www.baidu.com', timeout=3)
# print(response.status, response.url)
# print(response.getheaders())
# print(response.getheader("Server"))

"""
    封装请求
"""
url = "https://www.douban.com"
# url = "https://httpbin.org/post"
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"}
data = bytes(parse.urlencode({"name": "Jessica"}), encoding="utf-8")
req = urllib.request.Request(url=url, data=data, headers=headers, method="POST")
response = urllib.request.urlopen(req)
print(response.read().decode("utf-8")[0:387])
